//
//  UserBasicMessViewController.m
//  StraightTrain
//
//  Created by mk on 15/11/24.
//  Copyright (c) 2015年 mk. All rights reserved.
//

#import "UserBasicMessViewController.h"

@interface UserBasicMessViewController ()
{
   // BOOL showCityPick;
    BOOL updateMess;

    NSString * selectYixueID;//id
    NSString * selectXueshuID;//id
    
    NSMutableDictionary * dicUserData;
    
    int keyHeight;
    UITextField * textNow;
    
}
@end

@implementation UserBasicMessViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self clearView];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}

-(void)backNav:(id)sender
{
    if (updateMess)
    {
        AlertDelegate(alerTitle, @"是否放弃编辑资料", @"确定", @"取消")
    }else
        [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 创建城市pick
-(void)createCityPicker
{
    if (!pickCity)
    {
        pickCity = [[CityPickView alloc] init];
        pickCity.selectDelegate = self;
        pickCity.backgroundColor = [UIColor whiteColor];
        [pickCity setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.view addSubview:pickCity];
        NSDictionary *views = NSDictionaryOfVariableBindings(pickCity);
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0@1000-[pickCity]-0@1000-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:views]];
        
        NSLayoutConstraint *constraintHE = [NSLayoutConstraint constraintWithItem:self.view
                                                                        attribute:NSLayoutAttributeBottom
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:pickCity
                                                                        attribute:NSLayoutAttributeBottom
                                                                       multiplier:1
                                                                         constant:-202];
        [self.view addConstraint:constraintHE];
        
        NSLayoutConstraint *constraintV = [NSLayoutConstraint constraintWithItem:pickCity
                                                                       attribute:NSLayoutAttributeHeight
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:nil
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:1
                                                                        constant:202];
        [self.view addConstraint:constraintV];
    }
    
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    titleLabel.text = @"个人信息";
    [self createCityPicker];
    /*
         updateMess:1:表示已经编辑了资料等待提交 0:表示等待编辑资料
         USER_isProfile:1:表示已经编辑过了资料  0:表示还未编辑过
     */
    updateMess = ![[gProjConfig.dicUserData objectForKey:USER_isProfile] boolValue];
    dicUserData = [[NSMutableDictionary alloc]initWithCapacity:0];
    [self setViewData];
   // showCityPick = NO;
    [scrollerMain setAlwaysBounceVertical:YES];
}

#pragma mark 用户信息
-(void)setViewData
{
    BOOL isProfile = [[gProjConfig.dicUserData objectForKey:USER_isProfile] boolValue];
    if (isProfile)
    {
        SetHUDStartText(@"加载中..")
        NSString * strUrl = [NSString stringWithFormat:@"%@?username=%@&token=%@",[gProjConfig.dicAllUrl objectForKey:@"profileUrl"],[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];
        [[HttpClient manager]GET:strUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
            SetHUDHidden;
             
             dicUserData = [responseObject objectForKey:requestDataKey];
             textName.text = NullObjToString([dicUserData objectForKey:@"name"]);
             texDeptName.text = NullObjToString([dicUserData objectForKey:@"hpDeptName"]);
             texHpName.text = NullObjToString([dicUserData objectForKey:@"hospitalName"]);
             
             NSString * stracademic = NullObjToString([dicUserData objectForKey:@"academic_title"]);
             [btnaYTitle setTitle:stracademic forState:UIControlStateNormal];
             
             NSString * strClinical = NullObjToString([dicUserData objectForKey:@"clinical_title"]);
             [btncXTitle setTitle:strClinical forState:UIControlStateNormal];
            
             NSString * strCity = NullObjToString([dicUserData objectForKey:@"cityName"]);
             NSString * strstate = NullObjToString([dicUserData objectForKey:@"stateName"]);
            
             NSString * str = strCity;
             if (![strCity isEqualToString:strstate])
             {
                str = [NSString stringWithFormat:@"%@/%@",strstate,strCity];
             }
              [btnCity setTitle:str forState:UIControlStateNormal];
             pickCity.cityTitle.text = str;
             
             pickCity.selectProvince = -1;//默认为表示没修改
             pickCity.selectCity = -1;//默认为
             selectYixueID = @"";
             selectXueshuID = @"";
             
            [btnMore setTitle:@"编辑" forState:UIControlStateNormal];
  
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view)
         }];
    }else
    {
        [btnMore setTitle:@"保存" forState:UIControlStateNormal];
        NSMutableDictionary * dicProvince = [gProjConfig.arrCity objectAtIndex:pickCity.selectProvince];
        NSString * strProvince = [dicProvince objectForKey:@"state"];
        NSMutableArray * arrayCity = [dicProvince objectForKey:@"subCity"];
        NSMutableDictionary * dicCity = [arrayCity objectAtIndex:pickCity.selectCity];
        NSString * strCity = [dicCity objectForKey:@"city"];
        if (![strCity isEqualToString:strProvince])
           strCity = [NSString stringWithFormat:@"%@/%@",strProvince,strCity];
        [btnCity setTitle:strCity forState:UIControlStateNormal];
        pickCity.cityTitle.text = strCity;
        selectYixueID = @"";
        selectXueshuID = @"";
    }
    
    [self setViewUserInteractionEnabled];
}

-(void)setViewUserInteractionEnabled
{
    if (updateMess)
    {
        textName.userInteractionEnabled = YES;
        texDeptName.userInteractionEnabled = YES;
        texHpName.userInteractionEnabled = YES;
        btnaYTitle.userInteractionEnabled = YES;
        btncXTitle.userInteractionEnabled = YES;
        btnCity.userInteractionEnabled = YES;
        [btnCity setImage:[UIImage imageNamed:@"user_select_arrow_icon.png"] forState:UIControlStateNormal];
        [btnaYTitle setImage:[UIImage imageNamed:@"user_select_arrow_icon.png"] forState:UIControlStateNormal];
        [btncXTitle setImage:[UIImage imageNamed:@"user_select_arrow_icon.png"] forState:UIControlStateNormal];
        
    }else
    {
        textName.userInteractionEnabled = NO;
        texDeptName.userInteractionEnabled = NO;
        texHpName.userInteractionEnabled = NO;
        btnaYTitle.userInteractionEnabled = NO;
        btncXTitle.userInteractionEnabled = NO;
        btnCity.userInteractionEnabled = NO;
        [btnCity setImage:[UIImage imageNamed:@"user_select_arrow_hidden_icon.png"] forState:UIControlStateNormal];
        [btncXTitle setImage:[UIImage imageNamed:@"user_select_arrow_hidden_icon.png"] forState:UIControlStateNormal];
        [btnaYTitle setImage:[UIImage imageNamed:@"user_select_arrow_hidden_icon.png"] forState:UIControlStateNormal];
        
    }
}



-(IBAction)btnSelectCity:(id)sender
{
    [textNow resignFirstResponder];
   // pickCity.selectCity = 0;
   // pickCity.selectProvince = 0;
    [self showCityPickerData:YES];
}

-(IBAction)btnSelectYixueTitle:(id)sender
{
    [textNow resignFirstResponder];
    [self showCityPickerData:NO];
    
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"选择医学职称" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    sheet.tag = 100;
    for (NSString * strValue in [gProjConfig.dicClinicalTitle allKeys])
    {
        NSString * strTitle = [gProjConfig.dicClinicalTitle objectForKey:strValue];
        [sheet addButtonWithTitle:strTitle];
    }
    
    [sheet showInView:self.view];
}


-(IBAction)btnSelectXueshuTitle:(id)sender
{
    [textNow resignFirstResponder];
    [self showCityPickerData:NO];
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择学术职称"  delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:nil];
   
    for (NSString * strValue in [gProjConfig.dicAcademicTitle allKeys])
    {
        NSString * strTitle = [gProjConfig.dicAcademicTitle objectForKey:strValue];
        [sheet addButtonWithTitle:strTitle];
    }
    
    sheet.tag = 101;
    [sheet showInView:self.view];

}

#pragma mark 上传用户信息
-(void)rightBarAction:(id)sender
{
    [self clearView];
    
    if (!updateMess)
    {
        [btnMore setTitle:@"保存" forState:UIControlStateNormal];
        updateMess = !updateMess;
        [self setViewUserInteractionEnabled];
        return;
    }
    
    NSString * name = TextNsString(textName.text)
    NSString * yiyuan = TextNsString(texHpName.text)
    NSString * keshi = TextNsString(texDeptName.text)
    if(name.length==0)
    {
        Alert(alerTitle, @"请填写您的姓名", @"确定")
        return;
    }
    if(yiyuan.length==0)
    {
        Alert(alerTitle, @"请填写您的医院名字", @"确定")
        return;
    }
    if(keshi.length==0)
    {
        Alert(alerTitle, @"请填写您所属的科室", @"确定")
        return;
    }

    BOOL isProfile = [[gProjConfig.dicUserData objectForKey:USER_isProfile] boolValue];
  //  DLog(@"=gProjConfig.dicUserData修改前==%@",gProjConfig.dicUserData);
    if (!isProfile)//上传资料
    {
        if([selectYixueID isEqualToString:@""])
        {
            Alert(alerTitle, @"请选择医学职称", @"确定")
            return;
        }
        if([selectXueshuID isEqualToString:@""])
        {
            Alert(alerTitle, @"请选择学术职称", @"确定")
            return;
        }
        SetHUDStartText(@"提交资料..")
            
        NSMutableDictionary * dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"profile[username]"];
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"profile[token]"];
        [dicData setObject:textName.text forKey:@"profile[name]"];
            
            //省
        NSMutableDictionary * dicProvince = [gProjConfig.arrCity objectAtIndex:pickCity.selectProvince];
        NSString * strProvinceID = [dicProvince objectForKey:@"id"];
            //市
        NSMutableArray * arrayCity = [dicProvince objectForKey:@"subCity"];
        NSMutableDictionary * dicCity = [arrayCity objectAtIndex:pickCity.selectCity];
        NSString * strCityID = [dicCity objectForKey:@"id"];
        [dicData setObject:strProvinceID forKey:@"profile[state_id]"];//省
        [dicData setObject:strCityID forKey:@"profile[city_id]"];//城市
        [dicData setObject:texHpName.text forKey:@"profile[hospital_name]"];//医院
        [dicData setObject:texDeptName.text forKey:@"profile[hp_dept_name]"];//科室
        [dicData setObject:selectYixueID forKey:@"profile[clinical_title]"];//医学
        [dicData setObject:selectXueshuID forKey:@"profile[academic_title]"];//学术
        
        NSString * strUrl = NullObjToString([gProjConfig.dicAllUrl objectForKey:@"profileUrl"]);
        [[HttpClient manager]POST:strUrl
                                     parameters:dicData
                                        success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             //SetHUDHidden;
             SetHUDFinishedText(@"提交成功")
             [gProjConfig.dicUserData removeObjectForKey:USER_isProfile];
             [gProjConfig.dicUserData setObject:[[responseObject objectForKey:requestDataKey] objectForKey:@"id"] forKey:USER_id];
             [gProjConfig.dicUserData setObject:@"1" forKey:USER_isProfile];
             [gProjConfig writeToFile:USERPROFILE_FILENAME writeData:gProjConfig.dicUserData];
             
             // DLog(@"=gProjConfig.dicUserData修改后==%@",gProjConfig.dicUserData);
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view)
         }];
        
        return;
    }

  
            NSMutableDictionary * dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"username"];
            [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"token"];
            [dicData setObject:textName.text forKey:@"name"];
                //省
            if(pickCity.selectProvince > -1 && pickCity.selectCity > -1)
            {
                NSMutableDictionary * dicProvince = [gProjConfig.arrCity objectAtIndex:pickCity.selectProvince];
                NSString * strProvinceID = [dicProvince objectForKey:@"id"];
                //市
                NSMutableArray * arrayCity = [dicProvince objectForKey:@"subCity"];
                NSMutableDictionary * dicCity = [arrayCity objectAtIndex:pickCity.selectCity];
                NSString * strCityID = [dicCity objectForKey:@"id"];
                [dicData setObject:strProvinceID forKey:@"state_id"];//省
                [dicData setObject:strCityID forKey:@"city_id"];//城市
            }

    
            [dicData setObject:texHpName.text forKey:@"hospital_name"];//医院
            [dicData setObject:texDeptName.text forKey:@"hp_dept_name"];//科室
           if(![selectYixueID isEqualToString:@""])
           {
            [dicData setObject:selectYixueID forKey:@"clinical_title"];//医学
           }
           if(![selectXueshuID isEqualToString:@""])
           {
             [dicData setObject:selectXueshuID forKey:@"academic_title"];//学术
           }
                
            SetHUDStartText(@"修改资料..")
            NSString * strUrl = [NSString stringWithFormat:@"%@/%@", NullObjToString([gProjConfig.dicAllUrl objectForKey:@"profileUrl"]),NullObjToString([dicUserData objectForKey:@"id"])];
            [[HttpClient manager]PUT:strUrl
                              parameters:@{@"profile":dicData}
            success:^(AFHTTPRequestOperation *operation, id responseObject)
            {
                   // SetHUDHidden;
                SetHUDFinishedText(@"修改成功")
            } failure:^(AFHTTPRequestOperation *operation, NSError *error)
            {
                SetHUDHidden;
                HUDShowRequestError(error.domain, self.view)
            }];
}

-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [btnMore setTitle:@"编辑" forState:UIControlStateNormal];
    updateMess = !updateMess;
    [self setViewUserInteractionEnabled];
}



#pragma marl cityPickView
//-(void)selectPickData:(NSString *)city provinceData:(NSString *)province
//{
//    if ([city isEqualToString:province])
//    {
//         [btnCity setTitle:city forState:UIControlStateNormal];
//    }else
//    {
//         [btnCity setTitle:[NSString stringWithFormat:@"%@/%@",province,city] forState:UIControlStateNormal];
//    }
//    
//}

#pragma marl cityPickView

-(void)citytoolBarDoneClick:(id)sender
{
     [btnCity setTitle:pickCity.cityTitle.text forState:UIControlStateNormal];

}

#pragma mark showDataView
-(void)showCityPickerData:(BOOL)show
{
    for (NSLayoutConstraint *constraints in [pickCity.superview constraints])
    {
        if (constraints.firstItem == self.view && constraints.secondItem == pickCity && constraints.firstAttribute == NSLayoutAttributeBottom && constraints.secondAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^
             {
                 constraints.constant = (show?0:-202);
                 [self.view layoutIfNeeded];
             } completion:^(BOOL finished)
             {
             }];
            break;
        }
    }
    
}


#pragma mark actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.cancelButtonIndex == buttonIndex)
    {
        return;
    }
    if (actionSheet.tag == 100)//医学职称
    {
        NSString * strTitle = [[gProjConfig.dicClinicalTitle allValues] objectAtIndex:buttonIndex-1];
        [btnaYTitle setTitle:strTitle forState:UIControlStateNormal];
        selectYixueID = [[gProjConfig.dicClinicalTitle allKeys] objectAtIndex:buttonIndex-1];
    }
    else if (actionSheet.tag == 101)//学术职称
    {
        NSString * strTitle = [[gProjConfig.dicAcademicTitle allValues] objectAtIndex:buttonIndex-1];
        [btncXTitle setTitle:strTitle forState:UIControlStateNormal];
        
        selectXueshuID = [[gProjConfig.dicAcademicTitle allKeys] objectAtIndex:buttonIndex-1];
    }
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark textFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self showCityPickerData:NO];
    
    textNow = textField;
    [self changeViewFrame];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [scrollerMain setContentOffset:CGPointMake(0,0) animated:YES];
}


-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        [scrollerMain setContentOffset:CGPointMake(0,0) animated:YES];
        return NO;
    }
    return YES;
}

#pragma mark //当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    
    [self changeViewFrame];
}

-(void)changeViewFrame
{
    int bottomDistance;
 
    bottomDistance = appScreenHeight - textNow.bottom-64;//键盘预留高度
    
    int content = bottomDistance - (keyHeight + 30);//键盘到text得间距
    
    if (content < 0)
    {
        [scrollerMain setContentOffset:CGPointMake(0,-content) animated:YES];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [textNow resignFirstResponder];
}



-(IBAction)clearView
{
    [textNow resignFirstResponder];
    [self showCityPickerData:NO];
    [scrollerMain setContentOffset:CGPointMake(0,0) animated:NO];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex == buttonIndex)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
